package handlers

import (
	"data_service/models"
	"data_service/server"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 初始化用户业务服务
var userService = server.NewUserService()

// UpdateAvatarRequest 定义更新头像请求的结构
type UpdateAvatarRequest struct {
	UserID int                 `json:"user_id" binding:"required"`
	Config models.AvatarConfig `json:"config" binding:"required"` // 使用 models包中的统一定义
}

// UpdateAvatar 更新用户头像
func UpdateAvatar(c *gin.Context) {
	var req UpdateAvatarRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}
	if err := userService.UpdateAvatar(req.UserID, req.Config); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新头像失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "头像更新成功"})
}

// Register 处理新用户注册
func Register(c *gin.Context) {
	var req models.User
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}
	if req.Email == "" || req.Password == "" || req.Name == "" {
		fmt.Printf("参数：%v , %v , %v\n", req.Name, req.Password, req.Email)
		c.JSON(http.StatusBadRequest, gin.H{"error": "信息不能为空"})
		return
	}
	if userService.IsEmailExist(req.Email) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "邮箱已注册"})
		return
	}
	if err := userService.Register(&req); err != nil {
	fmt.Printf("注册数据库错误: %v\n", err)
	c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败: " + err.Error()})
	return
}
	c.JSON(http.StatusOK, gin.H{"message": "注册成功"})
}

// Login 处理用户登录
func Login(c *gin.Context) {
	var req struct {
		Email    string `json:"email" binding:"required,email"`
		Password string `json:"password" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的登录数据"})
		return
	}
	user, err := userService.Login(req.Email, req.Password)
if err != nil {
	fmt.Printf("登录错误: %v\n", err)
	c.JSON(http.StatusUnauthorized, gin.H{"error": "邮箱或密码错误: " + err.Error()})
	return
}
	if user.Status == "banned" {
		c.JSON(http.StatusForbidden, gin.H{"error": "您的账户已被封禁，请联系管理员"})
		return
	}
	token := generateToken(uint(user.ID))
	user.Password = ""
	user.CreatedAt = user.Model.CreatedAt
	c.JSON(http.StatusOK, gin.H{
		"message":    "登录成功",
		"token":      token,
		"user_id":    user.ID,
		"user_name":  user.Name,
		"role":       user.Role,
		"created_at": user.CreatedAt,
		"userInfo":   user,
	})
}

// generateToken 生成一个简单的认证Token (仅用于演示)
func generateToken(userId uint) string {
	return fmt.Sprintf("token_%d_%d", userId, time.Now().Unix()/3600)
}

// GetUserInfo 获取单个用户详细信息
func GetUserInfo(c *gin.Context) {
	userId := c.Param("id")
	user, err := userService.GetUserByID(userId)
	if err != nil || user == nil {
		fmt.Printf("获取用户信息错误: %v\n", err)
		c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在: " + err.Error()})
		return
	}
	user.Password = ""
	c.JSON(http.StatusOK, user)
}

// UpdateUserInfo 更新用户信息
func UpdateUserInfo(c *gin.Context) {
	userId := c.Param("id")
	var req struct {
		Name string `json:"name"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的参数"})
		return
	}
	idInt, _ := strconv.Atoi(userId)
	if err := userService.UpdateUserInfo(idInt, req.Name); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新用户信息失败"})
		return
	}
	user, err := userService.GetUserByID(userId)
	if err != nil {
		fmt.Printf("获取更新后用户信息错误: %v\n", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败: " + err.Error()})
		return
	}
	if user != nil {
		user.Password = ""
	}
	c.JSON(http.StatusOK, user)
}
